<template>
  <div class="address-box">
    <custom-header :title="'地址管理'" back="/user"></custom-header>
    <div class="address-item">
      <!-- 如果不是从个人中心页面进来的，就释放select功能；
      如果是从订单生成页面进来的，就需要选择地址，之后返回订单生成该页面，并带上地址id -->
      <van-address-list
        v-if="from != 'mine'"
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="select"
      />
      <van-address-list
        v-else
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
      />
    </div>
  </div>
</template>
  
  <script>
import { reactive, onMounted, toRefs } from "vue";
import CustomHeader from "components/CustomHeader.vue";
import { getAddressList } from "@/service/address";
import { useRoute, useRouter } from "vue-router";

export default {
  components: {
    CustomHeader,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const state = reactive({
      chosenAddressId: "1", // 被选中的地址id
      list: [], // 地址列表
      from: route.query.from
    });

    onMounted(() => {
      // 初始化数据
      initData();
    });

    const initData = async () => {
      // 获取地址列表
      const { data } = await getAddressList();
      if (!data) {
        state.list = [];
        return;
      }
      // 将数据构造成 AddressList 组件适配的格式
      state.list = data.map((item) => {
        return {
          id: item.addressId, // 地址id
          name: item.userName, // 收货人
          tel: item.userPhone, // 电话
          address: `${item.provinceName} ${item.cityName} ${item.regionName} ${item.detailAddress}`, //省、市、区
          isDefault: !!item.defaultFlag, // 是否为默认地址
        };
      });
    };

    // 添加方法，单击前往地址添加页面
    const onAdd = () => {
      router.push({
        path: "/address-edit",
        query: { type: "add" },
      });
    };

    // 编辑方法
    const onEdit = (item) => {
      router.push({
        path: "/address-edit",
        query: { type: "edit", addressId: item.id },
      });
    };

    // 筛选地址，返回“订单生成”页面
    const select = (item) =>{
      router.push({path:'/create-order', query: {addressId: item.id, from:state.from}})
    }

    return {
      ...toRefs(state),
      onAdd,
      onEdit,
      select,
    };
  },
};
</script>
  
<style lang="less">
@import "../theme/custom.less";
.address-box {
  .van-radio__icon {
    display: none;
  }
  .address-item {
    .van-button {
      background: @primary;
      border-color: @primary;
    }
  }
}
</style>